﻿# -*- coding: utf-8 -*-
#----------------------------------------------------------------------------
# Name:         config.py
# Purpose:      The main frame
#
# Author:       Zhang Kun
#
# Created:      1/21/08
# Copyright:    (c) 2007-2008 HanMingSoft, Inc.
# License:      Apache License v2.0
#----------------------------------------------------------------------------

import wx
from data import Customer
import config

class TextObjectValidator(wx.PyValidator):
     """ This validator is used to ensure that the user has entered something
         into the text object editor dialog's text field.
     """
     def __init__(self, item):
         """ Standard constructor.
         """
         wx.PyValidator.__init__(self)
         self.item = item

     def Clone(self):
         """ Standard cloner.

             Note that every validator must implement the Clone() method.
         """
         return TextObjectValidator(self.item)

     def Validate(self, win):
         """ Validate the contents of the given text control.
         """
         textCtrl = self.GetWindow()
         text = textCtrl.GetValue()

         if len(text) == 0:
             wx.MessageBox(u"请您输入%s。" % self.item, u"提示")
             textCtrl.SetBackgroundColour("pink")
             textCtrl.SetFocus()
             textCtrl.Refresh()
             return False
         else:
             textCtrl.SetBackgroundColour(
                 wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
             textCtrl.Refresh()
             return True

     def TransferToWindow(self):
         """ Transfer data from validator to window.

             The default implementation returns False, indicating that an error
             occurred.  We simply return True, as we don't do any data transfer.
         """
         return True # Prevent wxDialog from complaining.

     def TransferFromWindow(self):
         """ Transfer data from window to validator.

             The default implementation returns False, indicating that an error
             occurred.  We simply return True, as we don't do any data transfer.
         """
         return True # Prevent wxDialog from complaining.

class CustomerForm(wx.Panel):
    fields = ['code', 'name', 'tel', 'fax', 'email', 'linkman', 'linkman_tel', \
        'country', 'zip', 'address1', 'address2', 'address3', 'bank', 'account', 'tax_num', 'comment']
    input = {}
    customerId = None

    def __init__(self, parent):
        wx.Panel.__init__(self, parent, id=-1)
        sizer = wx.GridBagSizer(hgap=0, vgap=5)
        row = 1

        self.input['code'] = wx.TextCtrl(self, id=-1, validator = TextObjectValidator(u"客户编码"))
        self.input['code'].SetBackgroundColour(wx.Colour(255, 255, 204))
        sizer.Add(wx.StaticText(self, -1, u"客户编码：", size=(100, 20)), pos=(row, 1), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['code'], pos=(row, 2), span=(1,4), flag=wx.ALIGN_LEFT)

        row += 1
        self.input['name'] = wx.TextCtrl(self, id=-1, validator = TextObjectValidator(u"客户名称"))
        self.input['name'].SetBackgroundColour(wx.Colour(255, 255, 204))
        sizer.Add(wx.StaticText(self, -1, u"客户名称：", size=(100, 20)), pos=(row, 1), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['name'], pos=(row, 2), span=(1,4), flag=wx.EXPAND)

        row += 2
        self.input['tel'] = wx.TextCtrl(self, id=-1, size=(150, 20))
        sizer.Add(wx.StaticText(self, -1, u"电　　话：", size=(100, 20)), pos=(row, 1), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['tel'], pos=(row, 2), flag=wx.ALIGN_LEFT)
        
        self.input['fax'] = wx.TextCtrl(self, id=-1, size=(150, 20))
        sizer.Add(wx.StaticText(self, -1, u"传　　真：", size=(100, 20)), pos=(row, 4), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['fax'], pos=(row, 5), flag=wx.ALIGN_LEFT)

        row += 1
        self.input['email'] = wx.TextCtrl(self, id=-1, size=(150, 20))
        sizer.Add(wx.StaticText(self, -1, u"电子邮件：", size=(100, 20)), pos=(row, 1), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['email'], pos=(row, 2), flag=wx.ALIGN_LEFT)

        row += 2
        self.input['linkman'] = wx.TextCtrl(self, id=-1, size=(150, 20))
        sizer.Add(wx.StaticText(self, -1, u"联系人　：", size=(100, 20)), pos=(row, 1), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['linkman'], pos=(row, 2), flag=wx.ALIGN_LEFT)
        
        self.input['linkman_tel'] = wx.TextCtrl(self, id=-1, size=(150, 20))
        sizer.Add(wx.StaticText(self, -1, u"联系人电话：", size=(100, 20)), pos=(row, 4), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['linkman_tel'], pos=(row, 5), flag=wx.ALIGN_LEFT)

        row += 2
        self.input['country'] = wx.TextCtrl(self, id=-1, size=(150, 20))
        sizer.Add(wx.StaticText(self, -1, u"国　　家：", size=(100, 20)), pos=(row, 1), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['country'], pos=(row, 2), flag=wx.ALIGN_LEFT)

        self.input['zip'] = wx.TextCtrl(self, id=-1, size=(150, 20))
        sizer.Add(wx.StaticText(self, -1, u"邮　　编：", size=(100, 20)), pos=(row, 4), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['zip'], pos=(row, 5), flag=wx.ALIGN_LEFT)

        row += 1
        #self.input['address1'] = wx.TextCtrl(self, id=-1, size=(150, 20))
        self.input['address1'] = wx.ComboBox(self, id=-1, choices=config.PROVINCE, size=(150, 20))
        sizer.Add(wx.StaticText(self, -1, u"省(直辖市)：", size=(100, 20)), pos=(row, 1), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['address1'], pos=(row, 2), flag=wx.ALIGN_LEFT)

        self.input['address2'] = wx.TextCtrl(self, id=-1, size=(150, 20))
        sizer.Add(wx.StaticText(self, -1, u"市（县区）：", size=(100, 20)), pos=(row, 4), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['address2'], pos=(row, 5), flag=wx.ALIGN_LEFT)

        row += 1
        self.input['address3'] = wx.TextCtrl(self, id=-1)
        sizer.Add(wx.StaticText(self, -1, u"详细地址：", size=(100, 20)), pos=(row, 1), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['address3'], pos=(row, 2), span=(1,4), flag=wx.EXPAND)

        row += 2
        self.input['bank'] = wx.TextCtrl(self, id=-1, size=(150, 20))
        sizer.Add(wx.StaticText(self, -1, u"开户银行：", size=(100, 20)), pos=(row, 1), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['bank'], pos=(row, 2), flag=wx.ALIGN_LEFT)

        self.input['account'] = wx.TextCtrl(self, id=-1, size=(150, 20))
        sizer.Add(wx.StaticText(self, -1, u"银行帐号：", size=(100, 20)), pos=(row, 4), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['account'], pos=(row, 5), flag=wx.ALIGN_LEFT)

        row += 1
        self.input['tax_num'] = wx.TextCtrl(self, id=-1, size=(150, 20))
        sizer.Add(wx.StaticText(self, -1, u"税　　号：", size=(100, 20)), pos=(row, 1), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['tax_num'], pos=(row, 2), flag=wx.ALIGN_LEFT)

        row += 2
        self.input['comment'] = wx.TextCtrl(self, id=-1, size=(100, 80), style=wx.TE_MULTILINE )
        sizer.Add(wx.StaticText(self, -1, u"备　　注：", size=(100, 20)), pos=(row, 1), flag=wx.ALIGN_CENTER)
        sizer.Add(self.input['comment'], pos=(row, 2), span=(1,4), flag=wx.EXPAND)

        self.SetSizer(sizer)

    def Edit(self, id):
        customer = Customer()
        result = customer.GetById(id, self.fields)
        if not result:
            return
        self.customerId = id
        result = [(v != None) and v or '' for v in result]
        print result
        idx = 0
        for k in self.fields:
            #print k
            self.input[k].SetValue(result[idx])
            idx += 1

    def Save(self):
        if not self.Validate():
            return
        val = {}
        for k in self.fields:
            #if self.input[k].IsModified():
            val[k] = self.input[k].GetValue()

        customer = Customer()
        if self.customerId:
            customer.UpdateById(self.customerId, val)
        else:
            customer.Insert(val)
        print val

    def Delete(self):
        pass

import wx.grid

class DataGridTable(wx.grid.PyGridTableBase):
    def __init__(self, rowLabels, datas):
        wx.grid.PyGridTableBase.__init__(self)
        self.rowLabels = rowLabels
        self.datas = datas
#        print self.rowLabels
#        print self.datas
#        print len(self.datas)
        
    def GetNumberRows(self):
#        print "rows=%d" % len(self.datas)
#        print self.datas
        return len(self.datas)

    def GetNumberCols(self):
        #print len(self.rowLabels)
        return len(self.rowLabels)

    def IsEmptyCell(self, row, col):
        return self.datas[row][col] is not None

    def GetValue(self, row, col):
        value = self.datas[row][col]
        if value is not None:
            #print "value" + self.datas[row][col]
            return value
        else:
            return ''

    def SetValue(self, row, col, value):
        pass
        
    def GetColLabelValue(self, col):
        return self.rowLabels[col]

    def GetRowLabelValue(self, row):
        pass

class DataGrid(wx.grid.Grid):
    def __init__(self):
        grid.Grid.__init__(self, parent, -1)

class CustomerView(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, id=-1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.grid = wx.grid.Grid(self)
        self.grid.SetRowLabelSize(0)
        self.grid.EnableEditing(False)
        self.grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK, self.OnLeftDbClick)  
        sizer.Add(self.grid, 1, wx.EXPAND)
        self.SetSizer(sizer)
        self.Refresh()

    def Refresh(self):
        rowLabels = ["Id", u"客户编码", u"客户名称", u"电话", u"传真", u"电子邮件", u"联系人", u"联系人电话", \
        u"国家", u"邮编", u"省(直辖市)", u"市（县区）", u"详细地址", u"开户银行", u"银行帐号", u"税号", u"备注"]
        self.datas = Customer().GetMany(['id', 'code', 'name', 'tel', 'fax', 'email', 'linkman', 'linkman_tel', \
        'country', 'zip', 'address1', 'address2', 'address3', 'bank', 'account', 'tax_num', 'comment'])
        #print datas
        table = DataGridTable(rowLabels, self.datas)
        self.grid.SetTable(table, True, wx.grid.Grid.SelectRows)
        self.grid.AutoSizeColumns()
        #self.grid.SetColSize(0, 0)
        self.grid.SelectRow(0)

    def Print(self):
        from rpt_customer import CustomerList
        rptData = Customer().GetAll(['name', 'tel', 'fax', 'linkman', 'linkman_tel', \
        'country', 'zip', 'address1', 'address2', 'address3', 'bank', 'account', 'tax_num'])

        rpt = CustomerList(rptData)
        rpt.Draw()
        rpt.Preview()

    def OnLeftDbClick(self, event):
        #print 'Double click'
        id = int(self.grid.GetCellValue(event.GetRow(), 0))
        print 'Id:%d' % id
        if getattr(wx.GetApp(), 'frame'):
            wx.GetApp().frame.EditCustomerInfo(id)

if __name__ == "__main__":
    app = wx.PySimpleApp()
    app.username = 'Test'
    frame = wx.Frame(None, -1)
    sizer = wx.BoxSizer(wx.VERTICAL)
    panel = CustomerForm(frame)
    panel.Edit(1)
    panel.Save()
    sizer.Add(panel, 1, wx.EXPAND)
    panel2 = CustomerView(frame)
    sizer.Add(panel2, 2, wx.EXPAND)
    frame.SetSizer(sizer)
    frame.Show()
    app.MainLoop()